<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="110px">
      <el-form-item label="订单号" prop="gradOrdersNo">
        <el-input v-model="queryParams.gradOrdersNo" placeholder="请输入订单号" clearable />
      </el-form-item>
      <el-form-item label="订单任务类型" prop="gradOrdersTaskTypeId">
        <el-select v-model="queryParams.gradOrdersTaskTypeId" placeholder="请选择任务类型" clearable filterable>
          <el-option
            v-for="item in taskTypeOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskState">
        <el-select v-model="queryParams.taskState" placeholder="请选择任务状态" clearable>
          <el-option
            v-for="item in taskStateOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="提现状态" prop="withdrawalStatus">
        <el-select v-model="queryParams.withdrawalStatus" placeholder="请选择提现状态" clearable>
          <el-option
            v-for="item in withdrawalStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dashboard:task:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['dashboard:task:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple || !canDelete"
          @click="handleDelete"
          v-show="canDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['dashboard:task:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="订单号" align="center" prop="gradOrdersNo" />
      <el-table-column label="订单标题" align="center" prop="gradOrdersTitle" show-overflow-tooltip />
      <el-table-column label="订单任务类型" align="center" prop="gradOrdersTaskTypeId" :formatter="formatTaskType" />
      <el-table-column label="程序员" align="center" prop="programmerName" />
      <el-table-column label="最终任务金额" align="center" prop="finalTaskAmount" />
      <el-table-column label="任务状态" align="center" prop="taskState">
        <template slot-scope="scope">
          <el-select v-model="scope.row.taskState" @change="handleStatusChange(scope.row)">
            <el-option
              v-for="item in taskStateOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="提现状态" align="center" prop="withdrawalStatus">
        <template slot-scope="scope">
          <el-select v-model="scope.row.withdrawalStatus" @change="handleStatusChange(scope.row)">
            <el-option
              v-for="item in withdrawalStatusOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['dashboard:task:edit']"
          >修改</el-button>
          <el-button
            v-show="canDelete"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改订单任务(外部技术)对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="订单号" prop="gradOrdersNo">
          <el-input v-model="form.gradOrdersNo" placeholder="请输入订单号" :disabled="form.id != null" />
        </el-form-item>
        <el-form-item label="订单任务类型" prop="gradOrdersTaskTypeId">
          <el-select v-model="form.gradOrdersTaskTypeId" placeholder="请选择任务类型" filterable :disabled="form.id != null">
            <el-option
              v-for="item in taskTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <div v-if="form.id != null">
          <el-form-item label="程序员" prop="programmerName">
            <el-input v-model="form.programmerName" disabled />
          </el-form-item>
          <el-form-item label="最终任务金额" prop="finalTaskAmount">
            <el-input-number v-model="form.finalTaskAmount" :precision="2" :step="100" />
          </el-form-item>
          <el-form-item label="任务状态" prop="taskState">
            <el-select v-model="form.taskState" placeholder="请选择任务状态">
              <el-option
                v-for="item in taskStateOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="提现状态" prop="withdrawalStatus">
            <el-select v-model="form.withdrawalStatus" placeholder="请选择提现状态">
              <el-option
                v-for="item in withdrawalStatusOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask } from "@/api/dashboard/task"
import { listOrderTaskTypes } from "@/api/dashboard/orders_task_type";

export default {
  name: "Task",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单任务(外部技术)表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 任务类型选项
      taskTypeOptions: [],
      // 任务状态选项
      taskStateOptions: [
        { value: '0', label: '未中单' },
        { value: '1', label: '任务进行中' },
        { value: '2', label: '任务已完成' },
        { value: '3', label: '移交客户' },
        { value: '4', label: '任务结束' },
        { value: '5', label: '技术退单' },
        { value: '6', label: '客户退单' },
        { value: '7', label: '提现拒绝' }
      ],
      // 提现状态选项
      withdrawalStatusOptions: [
        { value: '0', label: '不可提现' },
        { value: '1', label: '提现首款可申请' },
        { value: '2', label: '已提现首款' },
        { value: '3', label: '尾款可申请' },
        { value: '4', label: '已提现尾款' },
        { value: '5', label: '首款提现失败' },
        { value: '6', label: '尾款提现失败' }
      ],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        gradOrdersNo: null,
        gradOrdersTaskTypeId: null,
        taskState: null,
        withdrawalStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      }
    }
  },
  computed: {
    // 检查是否有删除权限（只有售中主管和admin可以删除）
    canDelete() {
      const roles = this.$store.getters.roles || [];
      return roles.includes('售中主管') || roles.includes('admin');
    }
  },
  created() {
    this.getList()
    this.getTaskTypes();
  },
  methods: {
    /** 查询订单任务(外部技术)列表 */
    getList() {
      this.loading = true
      listTask(this.queryParams).then(response => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    getTaskTypes() {
      listOrderTaskTypes().then(response => {
        this.taskTypeOptions = response.rows.map(item => ({
          value: item.id,
          label: item.orderTaskName
        }));
      });
    },
    formatTaskType(row, column) {
      const taskType = this.taskTypeOptions.find(item => item.value === row.gradOrdersTaskTypeId);
      return taskType ? taskType.label : row.gradOrdersTaskTypeId;
    },
    // 表格状态修改
    handleStatusChange(row) {
      let text = '请确认是否修改?';
      this.$modal.confirm(text).then(function() {
        return updateTask(row);
      }).then(() => {
        this.$modal.msgSuccess("修改成功");
        this.getList();
      }).catch(function() {
        row.status = row.originalStatus;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        gradOrdersNo: null,
        gradOrdersTaskTypeId: null,
        taskState: null,
        finalTaskAmount: null,
        withdrawalStatus: null,
        acceptedProgrammerId: null,
        programmerName: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加订单任务(外部技术)"
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row ? row.id : (this.ids.length > 0 ? this.ids[0] : null)
      if (!id) {
        this.$modal.msgError("请选择要修改的记录")
        return
      }
      getTask(id).then(response => {
        this.form = response.data
        this.open = true
        this.title = "修改订单任务(外部技术)"
      }).catch(error => {
        console.error('获取任务详情失败:', error);
        this.$modal.msgError("获取任务详情失败: " + error.message);
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row ? row.id : this.ids
      if (!ids || (Array.isArray(ids) && ids.length === 0)) {
        this.$modal.msgError("请选择要删除的记录")
        return
      }
      this.$modal.confirm('是否确认删除订单任务(外部技术)编号为"' + ids + '"的数据项？').then(function() {
        return delTask(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(error => {
        console.error('删除失败:', error);
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('dashboard/task/export', {
        ...this.queryParams
      }, `task_${new Date().getTime()}.xlsx`)
    }
  }
}
</script>
